<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</head>

<body>
  <h1>拦截器的练习2</h1>
  <input type="text">
  <button type="submit">提交请求</button>
  <script>
    //获取节点
    const oIpt = document.querySelector('input')
    const oBnt = document.querySelector('button')
    let token;
    //实例化axios 
    const myAxios = axios.create({
      //配置对象
      baseURL: '/', //配置公共路径
      timeout: 10000, //配置请求超时时间
      headers: {

      }, //配置发送的自定义请求头
    })
    // 添加请求拦截器
    myAxios.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      // 增加一个token令牌
      token = 'safshafasgafaf'
      config.headers.token = token
      // 增加进度条
      NProgress.start();
      return config;
    }, function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    });

    // 添加响应拦截器
    myAxios.interceptors.response.use(function (response) {
      // 对响应数据做点什么
      //让进度条结束
      NProgress.done();
      return response.data;
    }, function (error) {
      // 对响应错误做点什么
      return Promise.reject(error.message);
    });
    //绑定点击事件
    oBnt.onclick = async function () {
      //获取到输入框的值
      let oIptvalue = oIpt.value;
      //尝试执行
      try {
        //
        const result = await myAxios.get('/getUser', {
          params: {
            userId: `${oIptvalue}`
          }
        })
        console.log('result', result.data);
      } catch (e) {
        console.log(e);
      }
    }
  </script>
</body>

</html>